<template>
  <div class="goods-add-page">
    <u-navbar
      :title="isAdd ? '添加购物' : '编辑购物'"
      :title-style="{ 'font-weight': 'bold', 'font-size': '18px' }"
      fixed
      placeholder
      @leftClick="handleBack"
    ></u-navbar>
    <div class="goods-add-content">
      <div class="gac-item" @click="focusInput(['detail', 'shopname'])">
        <span class="gac-required">*</span>
          <u--input
          clearable
          v-model="detail.shopname"
          class="shop-add-input"
          placeholder="请输入商品名"
          border="none"
          color="black"
        ></u--input>
        </div>
      <div
        class="gac-item"
        @click="showPicker = true"
      >
        <span class="gac-required required-status">*</span>
        <text
          v-if="pickvalue"
          class="search-selected-status"
        >
          {{ pickvalue }}
        </text>
        <text
          v-else
          class="search-status"
        >
          请选择等级
        </text>
        <u-picker
          :show="showPicker"
          :columns="columns"
          @cancel="showPicker = false"
          @confirm="onConfirm"
        ></u-picker>
        <u-icon
          color="#bfbfbf"
          name="arrow-right"
        ></u-icon>
      </div>
      <div class="gac-item">
        <span class="gac-required">*</span>
        <span
          v-if="detail.time"
          class="gac-date"
          @click="showDatePoup"
        >
          {{ getDay(detail.time) }}
        </span>
        <span
          v-else
          class="gac-date gac-empty"
          @click="showDatePoup"
        >
          选择准备购买日期
        </span>
        <u-icon
          color="#bfbfbf"
          name="arrow-right"
        ></u-icon>
      </div>

      <div class="gac-item gac-mark-item"   @click="focusInput(['detail', 'mark'])">
        <u--textarea
        clearable
          v-model="detail.mark"
        
          placeholder="请输入备注"
          border="none"
          count
          :max-length="50"
        ></u--textarea>
      </div>
    </div>
    <u-datetime-picker
      v-model="detail.time"
      :show="showdate"
      mode="date"
      @confirm="dateConfirm"
      @cancel="dateCancel"
    ></u-datetime-picker>
    <Speecher @handler="handlerSpeecher" @onclick="onclickSpeech"/>
    <u-modal
      :show="showdel"
      :show-cancel-button="true"
      content="确认要删除吗？"
      @confirm="delConfirm"
      @cancel="showdel = false"
    ></u-modal>
    <div class="gac-footer">
      <span
        v-if="!isAdd"
        class="gac-submit-del"
        @click="deleteClick"
      >
        删除
      </span>
      <span
        class="gac-submit-ok"
        @click="submitok"
      >
        提交
      </span>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import Speecher from '../../components/speecher/speecher.vue'

const statusTxts = {
  1: '马上',
  2: '次要',
  3: '未来',
}

export default {
  name: 'MyAdd',
  data() {
    return {
      detail: {
        mark: '',
        time: new Date()
      },
      showdel: false,
      isAdd: true,
      date: '',
      options: '',
      activeInputLevels: [],
      mark: '',
      showdate: false,
      maps: statusTxts,
      reverseMaps: Object.entries(statusTxts).reduce((acc, item) => {
        acc[item[1]] = item[0]
        return acc
      }, {}),
      pickvalue: statusTxts[1],
      showPicker: false,
      columns: [[...Object.values(statusTxts)]],
    }
  },
  components: {
     Speecher,
  },
  onLoad(options) {
    this.options = options || {}
    this.isMountedPageLoaded = true
    this.isAdd = !options.shopname
  },
  mounted() {
    if (!this.isAdd) {
      this.getdata()
    }
  },

  methods: {
    onclickSpeech() {
      this.speechClickTime = new Date().getTime()
    },
    focusInput(levels) {
      setTimeout(() => {
        const timer =  new Date().getTime()
        const intervalTime = Math.abs(timer - this.speechClickTime)
        // 透穿的行为应该是同时出现，所以，用300毫秒差不多
        if(intervalTime < 300){//间隔时间太少，说明是点击语音按钮时，透穿点击到了input，此时透穿应该无效
          return
        }
        this.activeInputLevels = levels
      }, 200);// 透穿的行为应该是同时出现，所以，用200毫秒等待差不多
    },
    handlerSpeecher(val) {
      const levels = this.activeInputLevels
      if(!levels?.length) return
      if(levels.length === 1){
        this[levels[0]] = val
      }
      if(levels.length === 2){
        this[levels[0]][levels[1]] = val
      }
      if(levels.length === 3){
        this[levels[0]][levels[1]][levels[2]] = val
      }
      if(levels.length === 4){
        this[levels[0]][levels[1]][levels[2]][levels[3]] = val
      }

      if(Array.isArray(this[levels[0]])){
        this[levels[0]] = [...this[levels[0]]]
      }else if(typeof this[levels[0]] === 'object'){
        this[levels[0]] = {...this[levels[0]]}
      }
      
      // 清除
      this.activeInputLevels = []
      
    },
    showDatePoup() {
      this.showdate = true
    },
    handleBack() {
      uni.navigateBack({
        delta: 1,
      })
    },
    async submitAdd() {
      const params = {
        shopname: this.detail.shopname,
        mark: this.detail.mark,
        status: this.reverseMaps[this.pickvalue],
        time: dayjs(this.detail.time).format('YYYY-MM-DD'),
      }
      const res = await this.$request.post('/shop/add', params)
      if (res.code === 200) {
        uni.showToast({
          title: '提交成功',
          duration: 1000,
          icon: 'success',
          mask: true,
        })
        setTimeout(() => {
          uni.navigateBack({
            delta: 1,
          })
        }, 1500)
      }
    },
    async submitedit() {
      const params = {
        shopname: this.options.shopname,
        mark: this.detail.mark,
        status: this.reverseMaps[this.pickvalue],
        time: dayjs(this.detail.time).format('YYYY-MM-DD'),
        newshopname: this.detail.shopname,
      }
      const res = await this.$request.post('/shop/update', params)
      if (res.code === 200) {
        uni.showToast({
          title: '提交成功',
          duration: 1000,
          icon: 'success',
          mask: true,
        })
        setTimeout(() => {
          uni.navigateBack({
            delta: 1,
          })
        }, 1500)
      }
    },
    async delConfirm() {
      try {
        const params = {
          shopname: this.options.shopname,
        }
        const res = await this.$request.post('/shop/del', params)
        if (res.code === 200) {
          uni.showToast({
            title: '删除成功',
            duration: 1000,
            icon: 'success',
            mask: true,
          })
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            })
          }, 1500)
        }
      } catch (e) {
        console.log(e)
      }
    },
    async deleteClick() {
      this.showdel = true
    },
    submitok() {
      if (this.isAdd) {
        this.submitAdd()
      } else {
        this.submitedit()
      }
    },
    dateCancel() {
      this.showdate = false
    },
    dateConfirm(va) {
      console.log(va)
      this.showdate = false
    },
    getDay(val) {
      return dayjs(val).format('YYYY年MM月DD日')
    },
    onConfirm(args) {
      this.pickvalue = args.value[0]
      this.showPicker = false
    },
    async getdata() {
      if (!this.options.shopname) return
      const response = await this.$request.post('/shop/list', {
        pageNo: 1,
        pageSize: 200,
        shopname: this.options.shopname,
      })
      const res = response && response.data
      let detail = (res && res[0]) || {}
      this.pickvalue = this.maps[detail.status]
      detail = { ...detail, mark: detail.mark || '' }
      this.detail = detail
    },
    back() {},
    clickAdd() {
      window.location.href = '/klm/shop/list'
    },
  },
}
</script>

<style lang="less">
.goods-add-page {
  .gac-item {
    .u-textarea {
      background-color: transparent;
    }
    .u-textarea__count {
      background-color: transparent !important;
    }
    .u-textarea__field {
      color: black;
    }
  }
}
</style>

<style lang="less" scoped>
@height-wrap: 44px;
@paddingbottom: 8px;
@fontColor: #bfbfbf;
@font-size: 15px;
.goods-add-page {
  .gac-required {
    color: red;
    font-size: 12px;
    margin-right: 7px;
  }
  .required-status {
  }
  .gac-item {
    display: flex;
    align-items: center;
    padding: 0 12px;
    margin: 0 16px;
    background: #f7f8fa;
    border-radius: 8px;
    height: 44px;
    margin-top: 12px;
  }

  .gac-mark-item {
    height: auto;
  }
  .gac-empty {
    color: #c8c9cc;
  }

  .search-status {
    color: @fontColor;
    font-size: @font-size;
  }
  .gac-date {
    font-size: @font-size;
  }
  .search-selected-status {
    color: black;
    font-size: @font-size;
  }

  .gac-date {
    flex: 1;
  }
  .gac-input {
    background: transparent;
    padding-left: 0;
  }
  .gac-status {
    background: transparent;
  }
  .right-icon {
    color: #bfbfbf;
  }

  .gac-submit-del,
  .gac-submit-ok {
    height: 100%;
    line-height: 44px;
    font-size: 16px;
    border-radius: 22px;
    padding-left: 28px;
    padding-right: 28px;
  }
  .gac-footer {
    display: flex;
    position: fixed;
    bottom: 0;
    //让图层更高
    z-index: 2;
    left: 0;
    right: 0;
    justify-content: center;
    align-items: center;
    height: 60px;
    background: #fff;
    box-shadow: 0 -2px 2px rgba(0, 0, 0, 0.05);
    padding: @paddingbottom 16px;
  }
  .gac-submit-del {
    background: #f7f8fa;
    color: #131212;
    margin-right: 12px;
    text-align: center;
  }
  .gac-submit-ok {
    flex: 1;
    background: #538fff;
    text-align: center;
    color: #fff;
  }
  .gac-del-diable {
    background: #f7f8fa;
    color: #979797;
  }

  .gac-ok-diable {
    background: #d8d8d8;
    color: #fff;
  }
}
</style>
